package www.sharetime.weshare.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import www.sharetime.weshare.R;
import www.sharetime.weshare.adapter.CityAdapter;
import www.sharetime.weshare.api.ShareTimeAPI;
import www.sharetime.weshare.base.BaseActivity;
import www.sharetime.weshare.event.AddTagEvent;
import www.sharetime.weshare.interfaces.ClickListener;
import www.sharetime.weshare.interfaces.RecyclerTouchListener;
import www.sharetime.weshare.response.CitySearchResponse;
import www.sharetime.weshare.utils.Constants;
import www.sharetime.weshare.utils.JsonUtils;
import www.sharetime.weshare.utils.NetUtil;
import www.sharetime.weshare.utils.ToastUtils;
import www.sharetime.weshare.utils.UIUtils;
import www.sharetime.weshare.view.TipInfoLayout;

/**
 * File Description  : 城市选择页面
 * @author : zhanggeng
 * @version : v1.0
 *          **************修订历史*************
 * @email : zhanggengdyx@gmail.com
 * @date : 2017/9/23 13:42
 */

public class CitySearchActivity extends BaseActivity {


    ArrayList<String> list = new ArrayList<>();

    ArrayList<String> searchList = new ArrayList<>();

    CityAdapter cityAdapter;
    @BindView(R.id.tv_tag_search_cancle)
    TextView tvTagSearchCancle;
    @BindView(R.id.img_del_search_content)
    ImageView imgDelSearchContent;
    @BindView(R.id.edt_search_content)
    EditText edtSearchContent;
    @BindView(R.id.recycler_city)
    RecyclerView recyclerCity;
    @BindView(R.id.tip_info)
    TipInfoLayout tipInfo;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_city_search;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);


        recyclerCity.setLayoutManager(new LinearLayoutManager(this));

        onRecyclerItemClick();

        edtSearchContent.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                onSearchKeyDown(keyCode, event);
                return false;
            }
        });
        //TODO: 当edittext 中内容发生变化的时候，进行处理
        edtSearchContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (edtSearchContent.getText().toString().equals("")) {
                    updateAdapter(list);
                }
            }
        });
    }

    private void updateAdapter(ArrayList<String> contentList) {
        recyclerCity.setVisibility(View.VISIBLE);
        if (cityAdapter != null) {
            cityAdapter.notifyDataChange(contentList);
        } else {
            cityAdapter = new CityAdapter(contentList, CitySearchActivity.this);
            recyclerCity.setAdapter(cityAdapter);
        }

        tipInfo.setVisibility(View.GONE);
    }

    private void onSearchKeyDown(int keyCode, KeyEvent event) {
        //是否是回车键
        if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
            //隐藏键盘
            ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(CitySearchActivity.this.getCurrentFocus()
                            .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);


            if (!edtSearchContent.getText().toString().trim().equals("")) {

                for (int index = 0; index < list.size(); index++) {
                    if (list.get(index).equals(edtSearchContent.getText().toString())) {
                        searchList.add(list.get(index));
                        updateAdapter(searchList);
                    }
                }
                if (searchList.size() == 0)
                    showToast("没有这个币种");
            } else {
                showToast("请输入币种");
            }
        }
    }


    @Override
    public void initData() {
        super.initData();
        //TODO: 发送网络，请求数据
        requestDataFromNet();
    }

    private void requestDataFromNet() {

        if (!NetUtil.isNetworkAvailable(CitySearchActivity.this)) {
            //TODO: 当网络状态发生变化时，做出相应动作，可以通过网络状态变化广播来实现
            tipInfo.setLoadError(Constants.NETWORK_CANNOT_USE);
            return;
        }

        tipInfo.setLoading();
        recyclerCity.setVisibility(View.GONE);

        OkHttpClient okHttpClient = new OkHttpClient();

        RequestBody requestBody = new FormBody.Builder().build();

        Request request = new Request.Builder()
                .addHeader("Authorization", "5_9f6cad7e465b4cf8803d41a3fcd8c77d")
                .url(ShareTimeAPI.BASE_URL + ShareTimeAPI.getGetDefaultCityList)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tipInfo.setLoadError(Constants.LOADERROR);
                        recyclerCity.setVisibility(View.GONE);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                try {
                    CitySearchResponse citySearchResponse = JsonUtils.toBean(
                            response.body().string(),
                            new TypeToken<CitySearchResponse>() {
                            }.getType());
                    for (int i = 0; i < citySearchResponse.getData().size(); i++) {
                        list.add(citySearchResponse.getData().get(i).getShortname());
                    }

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updateAdapter(list);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    tipInfo.setLoadError(Constants.LOADERROR);
                    recyclerCity.setVisibility(View.GONE);
                }
            }
        });
    }

    private void onRecyclerItemClick() {
        RecyclerTouchListener recyclerTouchListener = new RecyclerTouchListener(CitySearchActivity.this, recyclerCity, new ClickListener() {
            @Override
            public void onClick(View view, int position) {
                EventBus.getDefault().post(new AddTagEvent(CitySearchActivity.class.getSimpleName(),cityAdapter.getCitys().get(position)));
                UIUtils.closeActivity(CitySearchActivity.this);
            }

            @Override
            public void onLongClick(View view, final int position) {
            }
        });
        recyclerCity.addOnItemTouchListener(recyclerTouchListener);
    }


    /**
     * 当搜索框后面的 X 号 被点击后，触发相应动作
     */
    private void onImageDelClick() {
        edtSearchContent.setSelection(0);
        edtSearchContent.setText("");
        searchList.clear();
        //完整的list刷新数据
        updateAdapter(list);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            UIUtils.closeActivity(this);
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showToast(String remindMessage) {
        ToastUtils.showToastLong(CitySearchActivity.this, remindMessage);
    }

    @OnClick({R.id.tv_tag_search_cancle, R.id.img_del_search_content , R.id.tip_info})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_tag_search_cancle:
                UIUtils.closeActivity(this);
                break;
            case R.id.img_del_search_content:
                onImageDelClick();
                break;
            case R.id.tip_info:
                requestDataFromNet();
                break;
        }
    }
}
